<!-- @format -->

<template>
  <view
    class="comp-tab-panel"
    :class="{
      'comp-tab-panel--active': isActive,
      'comp-tab-panel--inactive': !isActive,
    }"
    v-show="animated || isActive"
  >
    <slot></slot>
  </view>
</template>

<script setup lang="ts">
  import { computed, inject, ref, onMounted } from 'vue';

  // 定义属性
  interface Props {
    /**
     * 标签名称，作为匹配的标识符
     */
    name: string | number;

    /**
     * 标签标题
     */
    title: string;

    /**
     * 是否禁用
     */
    disabled?: boolean;

    /**
     * 徽标内容
     */
    badge?: string | number;

    /**
     * 图标名称
     */
    icon?: string;
  }

  const props = withDefaults(defineProps<Props>(), {
    disabled: false,
  });

  // 获取父组件提供的上下文
  const parentActiveName = inject('activeName', ref(''));
  const animated = inject('animated', ref(false));
  const lazyRender = inject('lazyRender', ref(true));

  // 是否已渲染
  const inited = ref(!lazyRender.value);

  // 计算是否激活
  const isActive = computed(() => {
    const isActive = parentActiveName.value === props.name;
    if (isActive && !inited.value) {
      inited.value = true;
    }
    return isActive;
  });

  // 注册到父组件
  onMounted(() => {
    const registerPanel = inject('registerPanel', null) as
      | ((panel: any) => void)
      | null;
    if (registerPanel) {
      registerPanel({
        name: props.name,
        title: props.title,
        disabled: props.disabled,
        badge: props.badge,
        icon: props.icon,
      });
    }
  });
</script>

<style lang="scss">
  .comp-tab-panel {
    box-sizing: border-box;

    &--active {
      height: auto;
    }

    &--inactive {
      height: 0;
      overflow: hidden;
    }
  }
</style>
